package com.youhong.cuptime.blesdk;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.widget.Toast;

import java.util.List;

/*
 * 蓝牙设备的基类
 *         功能：
 *           1）保存设备属性
 *           2）获取设备属性
 *           3）结束服务，断开连接
 *           4）获取服务
 *           5）监视广播的属性
 *           6）数据加密
 *           7）数据解密
 *           
 * @author Kevin.wu
 * 
 */
public abstract class Bledevice {

    private boolean isAuto;
    private boolean isConncted;
    Intent serviceIntent;

    protected Context context = null;
    public String deviceName = null, deviceMac = null;
    protected BleService bleService = null;
    public BluetoothDevice device = null;
    // public RFStarBLEBroadcastReceiver delegate = null;
    public int bleDeviceType;

    public Bledevice(Context context, String address) {

        // this.deviceName = name;
        this.deviceMac = address;
        this.context = context;
        this.registerReceiver();
        if (serviceIntent == null) {
            serviceIntent = new Intent(this.context, BleService.class);
            this.context.bindService(serviceIntent, serviceConnection,
                    Service.BIND_AUTO_CREATE);
        }
    }

    public Bledevice(Context context) {

        // this.deviceName = name;
        this.context = context;
        MyLog.i("init device");
        this.registerReceiver();
        if (serviceIntent == null) {
            serviceIntent = new Intent(this.context, BleService.class);
            this.context.bindService(serviceIntent, serviceConnection,
                    Service.BIND_AUTO_CREATE);
        }
    }

    public void initServiceIntent() {
        if (serviceIntent == null) {
            serviceIntent = new Intent(this.context, BleService.class);
            this.context.bindService(serviceIntent, serviceConnection,
                    Service.BIND_AUTO_CREATE);
        }
    }

    /**
     * 是否连接
     *
     * @return
     */
    public boolean isConnected() {
        // return gatt.connect();
        return isConncted;
    }

    /**
     * 连接服务
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            bleService = null;

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bleService = ((BleService.LocalBinder) service).getService();
            if (deviceMac != null) {
                bleService.initBluetoothDevice(deviceMac, context);
            }
            // bleService.initBluetoothDevice(device,context);

        }
    };
    public BluetoothGattCharacteristic shujuCharateristic;
    public BluetoothGattCharacteristic shishiCharateristic;

    public void reConnected() {
        if (bleService == null)
            return;
        bleService.ReccnnectBluetoothDevice(deviceMac, context);
    }

    /**
     * 获取特征值
     *
     * @param characteristic
     */
    public void readValue(BluetoothGattCharacteristic characteristic) {
        if (characteristic == null) {
            MyLog.e("readValue characteristic is null");
        } else {
            bleService.readValue(this.device, characteristic);
        }
    }

    /**
     * 根据特征值写入数据
     *
     * @param characteristic
     */
    public void writeValue(BluetoothGattCharacteristic characteristic) {
        if (characteristic == null) {
            MyLog.e("writeValue characteristic is null");
        } else {
            if (bleService == null)
                return;
            bleService.writeValue(this.device, characteristic);
        }
    }

    public void disconnectDeviceAndClose(){
        if (bleService == null)
            return;
        bleService.setDisConnected();
    }
    /**
     * 消息使能
     *
     * @param characteristic
     * @param enable
     */
    public void setCharacteristicNotification(
            BluetoothGattCharacteristic characteristic, boolean enable) {

        if (characteristic == null) {
            MyLog.e("Notification characteristic is null");
        } else {
            MyLog.i("set Notification ");
            bleService.setCharacteristicNotification(this.device,
                    characteristic, enable);
        }
    }

    /**
     * 断开连接
     */
    public void disconnectedDevice() {
        if (bleService != null) {

            bleService.disconnect();
            bleService.setNeedReconnect(false);
            isConncted = false;
        }
//		if (bleService != null) {
//
//			bleService.disconnect();
////			this.context.unbindService(serviceConnection);
////			bleService=null;
////			serviceIntent=null;
//		}
        // if(serviceConnection != null)
        //this.context.unbindService(serviceConnection);
    }

    public void exitAll() {
        this.ungisterReceiver();
        if (bleService != null && isConncted) {
            bleService.disconnect();
        }
        if (serviceConnection != null)
            this.context.unbindService(serviceConnection);
    }


    /**
     * 监视广播的属性
     *
     * @return
     */
    protected IntentFilter bleIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BleService.ACTION_GAT_RSSI);
        intentFilter.addAction(BleService.ACTION_GATT_CONNECTING);
        // 自定义连接

        return intentFilter;
    }

    /**
     * 注册监视蓝牙设备（返回数据的）广播
     *
     * @param context
     * @param delegate
     * @param filter
     */
    public void registerReceiver() {
        gattUpdateRecevice = new MyBroadcastReceiver();
        this.context.registerReceiver(gattUpdateRecevice, this.bleIntentFilter());
    }

    /**
     * 注销监视蓝牙返回的广播
     */
    public void ungisterReceiver() {

        this.context.unregisterReceiver(gattUpdateRecevice);
    }

    /**
     * 初始化服务中的特征
     */
    protected void discoverCharacteristicsFromService() {
        // TODO Auto-generated method stub

    }

    /**
     * 接收蓝牙广播
     */
    private MyBroadcastReceiver gattUpdateRecevice;

    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (BleService.ACTION_GATT_SERVICES_DISCOVERED.equals(intent
                    .getAction())) {
                if (bleService == null) return;
                String address = bleService.getDeviceAddress();
                if (address == null || !address.equals(deviceMac)) return;
                List<BluetoothGattService> services = bleService.getSupportedGattServices();
                if (services == null) {
                    return;
                }
                for (BluetoothGattService service : services) {
                    for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
                        if (characteristic.getUuid().toString().contains("fff6")) {
                            shujuCharateristic = characteristic;
                        } else if (characteristic.getUuid().toString().contains("fff7")) {
                            shishiCharateristic = characteristic;// ����֪ͨ;
                            setCharacteristicNotification(characteristic, true);
                            isConncted = true;
                        }

                    }
                }

            } else if (BleService.ACTION_GATT_DISCONNECTED.equals(intent
                    .getAction())) {

                isConncted = false;
            }
        }
    }

}
